<template>
  <div>
    <!-- 默认input展示 -->
    <a-input v-if="showInput"
             :placeholder="placeholder"
             v-model="userName"
             :readOnly="true"
             :disabled="disabled"
             @click="openDialog">
    </a-input>
    <!-- showInput === false tagList展示 -->
    <section v-else>
      <a-tag size="normal"
             v-for="tag in newValue"
             :key="tag"
             closable
             disable-transitions="false"
             @click="removeTag(tag)"
             @close="removeTag(tag)">
        {{ labelDataList[tag] ? labelDataList[tag][pro.name] : "" }}

      </a-tag>

      <a-button size="small"
                plain
                round
                @click="openDialog">
        添加
      </a-button>
    </section>
    <DialogAntD ref="checkDialog"
                :not-allowed="notAllowed"
                :attrs="attrs"
                :data-list.sync="dataList"
                :type="'user'"
                :pro="pro"
                :slotTab="slotTab">
      <template v-for="(name) in slotTab"
                v-slot:[name.tab]="{tagLists}">
        <slot :name="name.tab"
              :tagLists="tagLists"></slot>
      </template>
    </DialogAntD>
  </div>
</template>

<script>
// import {
// 	listUserUnitTreeByParentId,
// 	listUserUnitTreeReverse
// } from '@/service/api/jurisdiction.js'
import DialogAntD from './components/DialogAntD.vue'
import unitUserMixins from './mixins/unitUserMixins'
import { getUnitAndUserListByParentId, getTreeUnitUsersByUserIds, getCrumbsByTopUnit } from '../api/select'
import PropTypes from '@zh/common-utils/prop-types'
const deepClone = require('clone')
export default {
  name: 'ZSelectUser',
  mixins: [unitUserMixins],
  components: { DialogAntD },
  props: {
    placeholder: PropTypes.string.def('请选择人员'),
    isLeader: PropTypes.bool.def(false).des('是否是领导'),
    existTopLeader: PropTypes.string.def('0').des('是否查询顶级领导'),
    notAllowed: PropTypes.array.def([]),
    containSelf: PropTypes.string.def('0').des('是否查询自己'),
    slotTab: PropTypes.array.def(null).des('插槽数据')
  },
  data () {
    return {
      attrs: {
        title: '请选择人员',
        type: 'user'
      },
      pro: {
        id: 'id',
        name: 'name',
        jobName: 'jobName'
      },
      userName: '',
      labelDataList: {},
      labelDataListInit: {}
    }
  },
  watch: {
    dataList: {
      handler (val) { }
    },
    notAllowed: {
      deep: true,
      handler (value) {
        if (!this.value) {
          return
        }
        value.forEach((item) => {
          if (this.value.indexOf(item) == -1) {
            this.value.push(item)
          }
        })
        this.getReverseData()
      }
    },
    topUnitId: {
      handler (topUnitId) {
        let labelDataList = {}
        labelDataList[topUnitId] = {
          name: this.topUnitName
        }
        this.labelDataList = { ...this.labelDataList, ...labelDataList }
        const this_ = this
        getCrumbsByTopUnit(topUnitId || '0', this.topUnitName).then((data) => {
          if (data) {
            const obj = {}
            data.unitIds.map((item, index) => {
              obj[item] = { name: data.unitNames[index] }
            })
            this_.labelDataList = { ...this_.labelDataList, ...obj }
            this_.labelDataListInit = JSON.parse(JSON.stringify(obj))
          }
        })
      },
      deep: true,
      immediate: true
    },
    slotTab: {
      handler (slotTab) {
        // if (slotTab) {
        //   let str = []
        //   slotTab.map(item => {
        //     item.data.map(d => {
        //       str.push(d.name)
        //     })
        //   })
        //   let arr = [...new Set((this.userName + (this.userName && str.length ? '、' : '') + str.join('、')).split('、'))]
        //   this.userName = arr.join('、')
        // }
      },
      deep: true,
      immediate: true
    }
  },
  mounted () {

  },
  methods: {
    // 打开弹出框
    openDialog () {
      if (this.disabled) {
        return
      }
      // 初始化数据
      const breadcrumbListsInit = Object.keys(this.labelDataListInit)
      this.$refs.checkDialog.breadcrumbLists = breadcrumbListsInit
      this.loadNode(breadcrumbListsInit[breadcrumbListsInit.length - 1])
      this.$refs.checkDialog.tagLists = deepClone(this.newValue)
      this.$refs.checkDialog.openDialog()
    },
    // 清空方法
    clear () {
      this.userName = ''
    },
    /**
     * 数据加载
     * @param {*} parentId 上级id
     */
    loadNode (parentId) {
      this.listLoading = true
      if (!parentId) {
        return
      }
      if (parentId != 0 && parentId.substring(0, 4) == this.userIdFlag) {
        parentId = parentId.substring(4, parentId.length)
      }
      getUnitAndUserListByParentId(parentId, this.cantianSelf, this.isIncludChildren,this.label,this.extend).then((data) => {
        if (data) {
          const userList = data.filter(item => {
            return item.type == 2
          })
          const unitList = data.filter(item => {
            return item.type == 1
          })
          const otherList = data.filter(item => {
            return item.type != 1 && item.type != 2
          })
          const List = [...userList, ...unitList, ...otherList]
          this.dataList = []
          let labelDataList = {}
          List.forEach((item) => {
            if (item.type == 1) {
              item.id = this.userIdFlag + item.id
            }
            this.dataList.push(item.id)
            labelDataList[item.id] = item
          })
          this.labelDataList = { ...this.labelDataList, ...labelDataList }
          this.listLoading = false
        }
      })
    },
    // 获取返现数据
    getReverseData () {
      return new Promise((resolve, reject) => {
        if (!this.newValue || this.newValue.length == 0) {
          resolve([])
          this.userName = ''
          this.$emit('change', [], [])
          if (this.slotTab) {
            let str = []
            this.slotTab.map(item => {
              item.data.map(d => {
                str.push(d.name)
              })
            })
            let arr = [...new Set((this.userName + (this.userName && str.length ? '、' : '') + str.join('、')).split('、'))]
            this.userName = arr.join('、')
          }
          return
        }
        getTreeUnitUsersByUserIds(this.newValue.join(',') || '',this.deep).then((data) => {
          if (data) {
            if (this.slotTab) {
              this.$emit('change', this.newValue, { data: data, slotTab: this.slotTab })
            } else {
              this.$emit('change', this.newValue, data)
            }
            this.userName = ''
            let labelDataList = {}
            data.forEach((item, index) => {
              // 缓存数据
              labelDataList[item.id] = item
              // 拼接选中人员名称
              this.userName += item.fullUserName
              if (index < data.length - 1) {
                this.userName += '、'
              }
            })
            if (this.slotTab) {
              let str = []
              this.slotTab.map(item => {
                item.data.map(d => {
                  str.push(d.name)
                })
              })
              let arr = [...new Set((this.userName + (this.userName && str.length ? '、' : '') + str.join('、')).split('、'))]
              this.userName = arr.join('、')
            }
            this.labelDataList = { ...this.labelDataList, ...labelDataList }
            resolve(data)
          }
        })
      })
    }
  }
}
</script>

<style lang="less" scoped>
::v-deep .el-tag {
  // margin-right: 5px;
  margin: 3px;
}
.el-button {
  margin-left: 5px;
}
::v-deep .el-input__suffix {
  right: 10px;
}
</style>
